package org.jeecg.modules.util;

import org.apache.commons.lang3.StringUtils;

public class ConvertUtil {

    /**
     * 十六进制转为byte数组
     *
     * @param hex 十六进制字符串
     * @return byte数组
     */
    public static byte[] hex2Bytes(String hex) {
        if (hex.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hex.length() / 2];
            int j = 0;
            for (int i = 0; i < hex.length(); i += 2) {
                result[j++] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
            }
            return result;
        }
    }

    /**
     * 十六进制byte数组转为十六进制字符串
     *
     * @param bytes 十六进制byte数组
     * @return 十六进制字符串
     */
    public static String bytes2HexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length);
        String sTmp;

        for (int i = 0; i < bytes.length; i++) {
            sTmp = Integer.toHexString(0xFF & bytes[i]);
            if (sTmp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTmp.toUpperCase());
        }

        return sb.toString();
    }

    /**
     * 16进制指定长度
     *
     * @param hexStr
     * @param len
     * @return
     */
    public static byte[] getHexStrWithLength(String hexStr, int len) {
        return ConvertUtil.hex2Bytes(StringUtils.leftPad(hexStr, len, "0"));
    }

    public static String getStrWithLength(String hexStr, int len){
        return StringUtils.leftPad(hexStr, len, "0");
    }

    public static byte[] getByteByInt(int stationLength) {
        byte[] result = new byte[4];
        result[0] = (byte)((stationLength >> 24) & 0xFF);
        result[1] = (byte)((stationLength >> 16) & 0xFF);
        result[2] = (byte)((stationLength >> 8) & 0xFF);
        result[3] = (byte)(stationLength & 0xFF);
        return result;
    }

    public static byte[] getByteByShort(short stationLength) {
        byte[] result = new byte[2];
        result[0] = (byte)((stationLength >> 8) & 0xFF);
        result[1] = (byte)(stationLength & 0xFF);
        return result;
    }
}
